package com.ruix.app.ui.usercenter;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.OSS;
import com.ruix.app.R;
import com.ruix.app.cache.CacheFactory;
import com.ruix.app.constant.RuiXConstant;
import com.ruix.app.manager.UserManager;
import com.ruix.app.mapper.OssTokenMapper;
import com.ruix.app.mapper.UserMapper;
import com.ruix.app.model.OssToken;
import com.ruix.app.model.User;
import com.ruix.app.model.UserInfo;
import com.ruix.app.network.ALUploadFileParam;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.ui.base.BaseActivity;
import com.ruix.app.util.ImageClipUtil;
import com.ruix.app.util.LogUitl;
import com.ruix.app.widget.CommonTitleBar;
import com.ruix.app.widget.clip.ClipImageLayout;

import java.io.File;
import java.util.ArrayList;

import io.reactivex.disposables.Disposable;

/**
 * Created by hadexs on 2017/5/7.
 */

public class EditePictureActivity extends BaseActivity{

    private Bitmap bitmap;
    private Uri originalUri;
    private ClipImageLayout mClipImageLayout;
    private OSS ossClient;
    private OssToken ossToken;
    private boolean isuploading;


    @Override
    protected int loadViewLayout() {
        return R.layout.activity_edite_picure;
    }

    @Override
    protected void initView() {
        setTitle("编辑头像");

        mClipImageLayout = (ClipImageLayout) findViewById(R.id.clip_image_layout);
        Intent intent = getIntent();
        String picFrom = intent.getStringExtra("picSource");
        if ("camera".equals(picFrom)) {
            originalUri = intent.getParcelableExtra("uri");
//            originalUri = Uri.parse(Uri.fromFile(new File(ImageClipUtil.getCameraFileName(this))).toString());
//            ;
        } else if ("photo".equals(picFrom)) {
            originalUri = intent.getParcelableExtra("uri");
        }
        try {
            bitmap = ImageClipUtil.getBitmapFromUri(this, originalUri, "camera".equals(picFrom));
            mClipImageLayout.setBitmap(bitmap);
        } catch (Exception e) {
            finish();
        }
    }

    @Override
    protected void initLocalData() {
        loadOssTokenWithCache();
    }

    private void loadOssTokenWithCache(){
        String uid = UserManager.getCurrentUser().getID();
        ossToken =  CacheFactory.loadOssToken(uid);
        if (ossToken != null && !TextUtils.isEmpty(ossToken.getSecurityToken())){
            buildOssClient();
        } else {
            loadOssToken();
        }
    }

    private void buildOssClient(){
        if (ossToken != null) {
            ossClient = ALUploadFileParam.loadOSSClient(this, ossToken);
        }
    }

    private void loadOssToken(){
        RequestFactory.getOssToken(new OssTokenMapper(), new RXObserver<OssToken>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(OssToken value) {
                if (value != null && !TextUtils.isEmpty(value.getSecurityToken())){
                    ossToken = value;
                    buildOssClient();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    @Override
    protected void initListener() {
        CommonTitleBar titleBar = getTitleBar();
        TextView titleBarRightBtn = titleBar.getRightBtn();
        titleBarRightBtn.setText("保存");
        titleBarRightBtn.setTextColor(getResources().getColor(R.color.color_33));
        titleBarRightBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buildBitmapAndUpload();
            }
        });

    }

    private void buildBitmapAndUpload(){
        if (!isuploading) {
            isuploading = true;
            String path = buildBitmap();
            uploadPhoto(path);
        }

    }

    private String buildBitmap(){
        Bitmap bitmap = mClipImageLayout.clip();// 进行图片裁剪
        return ImageClipUtil.saveBitmapToExternalTem(getCacheDir().getAbsolutePath()+"avatar.png", bitmap);//保存图片到本地
    }

    private void uploadPhoto(String avatarPath) {
        if (TextUtils.isEmpty(avatarPath) || ossClient == null){
            isuploading = false;
            return;
        }

        ArrayList selectedPhotos = new ArrayList();
        selectedPhotos.add(avatarPath);

        showLoading();//
        ALUploadFileParam param = new ALUploadFileParam();
        param.setUid(UserManager.getCurrentUser().getID());
        param.setPathes(selectedPhotos);
        param.setOssClient(ossClient);
        param.setOssToken(ossToken);
        RequestFactory.uploadFileToALY(param, new RXObserver<ArrayList<String>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ArrayList<String> value) {
                if (value != null && value.size() > 0) {
                    saveUerAvatar(value.get(0));
                }
            }

            @Override
            public void onError(Throwable e) {
                showErrorTip(e.getMessage());
                dismissLoading();
                isuploading = false;
            }

            @Override
            public void onComplete() {

            }
        });
    }


    private void saveUerAvatar(String path){
        if (TextUtils.isEmpty(path)){
            return;
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setAvatarPath(path);
        RequestFactory.editUserinfo(userInfo,new UserMapper(), new RXObserver<User>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(User value) {
                if (value != null && !TextUtils.isEmpty(value.getID())){
                    UserManager.sharedInstance().setCurrentUser(value);
                    UserManager.sharedInstance().saveCurrentUser();
                    sendBroadcast(new Intent(RuiXConstant.NOTICE_CHANGE_USER_INFO));
                }

            }

            @Override
            public void onError(Throwable e) {
                dismissLoading();
                resolveException(e);
                isuploading = false;
            }

            @Override
            public void onComplete() {
                isuploading = false;
                dismissLoading();
                finish();
            }
        });

    }

}
